package com.defect.util;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

/*
 * 自定义日期类型转换类
 * 实现接口时需要定义两个泛型，第一个是待转换类型，第二个是目标类型
 */
@Component
public class DateConversion implements Converter<String, Date>{

	@Override
	public Date convert(String source) {
		System.out.println(source);
		Date date=null;
		try {
			//定义正则表达式校验日期格式
			String pattern1="[0-9]{4}-[0-9]{2}-[0-9]{2}";
			SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
			String pattern2="[0-9]{4}/[0-9]{2}/[0-9]{2}";
			SimpleDateFormat format2 = new SimpleDateFormat("yyyy/MM/dd");
			if(source==null||"".equals(source)) {
				return date;
			}else if(source.matches(pattern1)) {
				date=format1.parse(source);
			}else if(source.matches(pattern2)) {
				date=format2.parse(source);
			}else {
				throw new RuntimeException("日期格式错误");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return date;
	}
}
